package com.yjj.im.ui;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.yjj.im.R;
import com.yjj.im.Utils.BitMapUtil;
import com.yjj.im.Utils.BluetoothUtil;
import com.yjj.im.Utils.BlutetoothPrinterUtils;
import com.yjj.im.Utils.Constant;
import com.yjj.im.Utils.ESCUtil;
import com.yjj.im.Utils.HandlerUtils;
import com.yjj.im.Utils.ThreadPoolManager;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;


import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import com.yjj.im.Utils.AFinalHttp;
import com.yjj.im.Utils.GsonFomater;
import com.yjj.im.Utils.Utils;
import com.yjj.im.Utils.WebSocketListener;
import com.yjj.im.bean.Carbean;
import com.yjj.im.bean.Company;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import com.yjj.im.bean.DataBean;
import com.yjj.im.bean.ResultBean;

public class MessageActivity extends Activity implements View.OnClickListener, WebSocketListener, CompoundButton.OnCheckedChangeListener {
    @BindView(R.id.CirleL)
    ImageView CirleL;
    @BindView(R.id.CirleR)
    ImageView CirleR;

    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_item)
    TextView tv_item;
    @BindView(R.id.tv_item1)
    TextView tv_item1;
    @BindView(R.id.tv_item2)
    TextView tv_item2;
    @BindView(R.id.tv_item3)
    TextView tv_item3;
    @BindView(R.id.tv_item4)
    TextView tv_item4;
    @BindView(R.id.tv_item5)
    TextView tv_item5;
    @BindView(R.id.tv_item6)
    TextView tv_item6;
    @BindView(R.id.tv_item7)
    TextView tv_item7;
    @BindView(R.id.tv_item8)
    TextView tv_item8;
    @BindView(R.id.tv_item9)
    TextView tv_item9;
    @BindView(R.id.tv_item10)
    TextView tv_item10;
    @BindView(R.id.value_item)
    TextView value_item;
    @BindView(R.id.value_item1)
    TextView value_item1;
    @BindView(R.id.value_item2)
    TextView value_item2;
    @BindView(R.id.value_item3)
    TextView value_item3;
    @BindView(R.id.value_item4)
    TextView value_item4;
    @BindView(R.id.value_item5)
    TextView value_item5;
    @BindView(R.id.value_item6)
    TextView value_item6;
    @BindView(R.id.value_item7)
    TextView value_item7;
    @BindView(R.id.value_item8)
    TextView value_item8;
    @BindView(R.id.value_item9)
    TextView value_item9;
    @BindView(R.id.value_item10)
    TextView value_item10;
    @BindView(R.id.value_item11)
    TextView value_item11;
    @BindView(R.id.shengli)
    LinearLayout shengli;
    @BindView(R.id.haomali)
    LinearLayout haomali;
    //声明spinner对象
    private Button btnSendMessage;
    private Button modifyButtonn;

//    private String clientId;
    //服务器连接IP以及端口
    private String host = "tcp://47.92.132.44:1883";
    private String prot = "";
    private String userName="admin";
    private String password="admin";
    private String myTopic = "mqtt123";
    public static  String baseUrl ="http://we.cmczc.cn/";
    public static String currentId = "";
    public static String currentUser = "";
    public static String clientName = "";
    public static String isAuto = "";
    private Handler handler;
    private EditText sendTopic;
    private EditText sendMessage;
    private TextView title;
    private int qos;
    //  Button loginButton;
    private MqttClient client;
    ImageView carNoImg;


    private static final String TAG = "BlutetoothPrinter";

    private MqttConnectOptions options;

    private ScheduledExecutorService scheduler;
//    private final String  PRINTER_NORMAL_ACTION = "com.iposprinter.iposprinterservice.NORMAL_ACTION";
//    private final String  GET_CUST_PRINTAPP_PACKAGENAME_ACTION = "android.print.action.CUST_PRINTAPP_PACKAGENAME";
    /*循环打印类型*/
    private final int  MULTI_THREAD_LOOP_PRINT  = 1;
//    private final int  DEFAULT_LOOP_PRINT       = 0;

    /*定义打印机状态*/
    private final int PRINTER_NORMAL = 0;
//    private final int PRINTER_ERROR_UNKNOWN = 5;
    /*打印机当前状态*/
//    private int printerStatus = PRINTER_ERROR_UNKNOWN;
    //循环打印标志位
//    private       int  loopPrintFlag            = DEFAULT_LOOP_PRINT;

    private boolean isBluetoothOpen = false;
    private TextView info;
    private Random random = new Random();
    private HandlerUtils.PrinterHandler mPrinterHandler;
    private final int MSG_TEST                               = 1;
    private final int MSG_IS_NORMAL                          = 2;
    private BluetoothAdapter mBluetoothAdapter = null;
    private BluetoothDevice mBluetoothPrinterDevice = null;
//    private BluetoothSocket socket = null;

    public static Context context;
    ArrayList<String> compayIdlist = new ArrayList<>();
    ArrayList<String> compayNamelist = new ArrayList<>();
    ArrayList<String> itemIdlist = new ArrayList<>();
    ArrayList<String> itemNamelist = new ArrayList<>();
    private ArrayAdapter<String> adapter;
    private CheckBox checkBox;
    private String  company,product,company1,note,car;
    private ImageView iv_menu;
    private PopupMenu popupMenu;
    public static HashMap<String,String> compayKeyList = new HashMap<String, String>();
    private PopupWindow.OnDismissListener dismissListener=new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            setTextImage(R.drawable.icon_down);
        }
    };
    private ArrayList<DataBean> list = new ArrayList<>();
    /**
     * popupwindow��ʾ��ListView��item����¼�
     */
    private AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
            mSpinerPopWindow.dismiss();
            if(selectViewIndex == 0 ){
                company = compayIdlist.get(position);
                tvValue.setText(compayNamelist.get(position));
            }else if(selectViewIndex == 1 ){
                company1 = compayIdlist.get(position);
                tvValue1.setText(compayNamelist.get(position));
            }else if(selectViewIndex == 2){
                tvValue2.setText(itemNamelist.get(position));
                product = itemIdlist.get(position);
            }
            selectViewIndex = -1;
//            if(view.equals(tvValue)){
//                tvValue.setText(compayNamelist.get(position));
//            }else if(view.equals(tvValue1)){
//                tvValue1.setText(compayNamelist.get(position));
//            }else if(view.equals(tvValue2)){
//                tvValue2.setText(itemNamelist.get(position));
//            }

        }
    };

    private SpinerPopWindow<String> mSpinerPopWindow;
    private TextView tvValue;
    private TextView tvValue1;
    private TextView tvValue2;
    private int selectViewIndex = -1;
    private boolean isModifyButton = true;
    private int isSingle = 2;
    private Button singleButton;
    private LinearLayout promptView;
    private  BlutetoothPrinterUtils blutetoothPrinterUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);//android:background="@color/content_color"
        initShare();
        setContentView(R.layout.activity_message);
        context = this;
        blutetoothPrinterUtils = new BlutetoothPrinterUtils();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);



        init();
        tv_title.setText("称重");
        tvValue = (TextView) findViewById(R.id.tv_value);
        tvValue.setOnClickListener(this);
//        mSpinerPopWindow = new SpinerPopWindow<String>(this, list,itemClickListener);
//        mSpinerPopWindow.setOnDismissListener(dismissListener);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(msg.what == 1) {
                    //接收订阅消息
                    title.setText((String) msg.obj);
//                    Toast.makeText(MessageActivity.this, (String) msg.obj,
//                            Toast.LENGTH_SHORT).show();
                } else if(msg.what == 2) {
                    Log.i("lymain", "handler=" + msg.what);
                    Toast.makeText(MessageActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                    try {
                        //订阅消息（订阅主题是test/topic的消息）
                        client.subscribe(myTopic, 1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if(msg.what == 3) {
                    Toast.makeText(MessageActivity.this, "连接失败，系统正在重连", Toast.LENGTH_SHORT).show();
                }else if(msg.what == 4){
                    Log.i("lymain","发布信息：QOS="+qos+";  topic="+myTopic+";  内容："+sendMessage.getText().toString());
                   try{
                       //发布信息  参数说明（主题，内容，qos，是否保留）
                       client.publish(myTopic,sendMessage.getText().toString().getBytes(),qos,false);
                   }catch (Exception e){

                   }

                }else if(msg.what == 4){
//                    adapter.addAll(compayNamelist);
//                    spinner.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                }else if(msg.what == 5){
                   Carbean bean = (Carbean) msg.obj;
                    sendTopic.setText(bean.valu);
//                    byte[] decodedStrinng = Base64.decode(bean.carimg,Base64.DEFAULT);
//                    Bitmap bitmap = BitmapFactory.decodeByteArray(decodedStrinng,0,decodedStrinng.length);
//                    carNoImg.setImageBitmap(bitmap);
                }else if(msg.what == 7){
                    String[] ifrared = (String[]) msg.obj;
                    if(ifrared != null && ifrared.length>2){
                        String ifrared1 = ifrared[1];
                        String ifrared2 = ifrared[2].substring(0,1);
                        if(ifrared1.equals("0")){
                            CirleL.setBackgroundResource(R.drawable.layout_circle);
                        }else if(ifrared1.equals("1")){
                            CirleL.setBackgroundResource(R.drawable.layout_circle_r);
                        }
                        if(ifrared2.equals("0")){
                            CirleR.setBackgroundResource(R.drawable.layout_circle);
                        }else if(ifrared2.equals("1")){
                            CirleR.setBackgroundResource(R.drawable.layout_circle_r);
                        }
                    }
                }

            }
        };
        startReconnect();
//        if(!client.isConnected()) {
//            connect();
//        }
        mPrinterHandler = new HandlerUtils.PrinterHandler(blutetoothPrinterUtils.mHandlerIntent);
        BlutetoothPrinterUtils.setPriterHadler(mPrinterHandler);
        btnSendMessage.setOnClickListener(this);
        modifyButtonn.setOnClickListener(this);

        tvValue1 = (TextView) findViewById(R.id.tv_value1);
        tvValue1.setOnClickListener(this);
        tvValue2 = (TextView) findViewById(R.id.tv_value2);

//        tvValue2.setOnClickListener(this);
        mSpinerPopWindow = new SpinerPopWindow<String>(this, compayNamelist,itemClickListener);
        mSpinerPopWindow.setOnDismissListener(dismissListener);
    }



    @OnClick({R.id.rootview,R.id.topview,R.id.tv_value,R.id.tv_value1,R.id.tv_value2,R.id.iv_menu,R.id.iv_back,R.id.single_ly,
            R.id.jingte, R.id.tianjinte, R.id.yute, R.id.hute, R.id.jibeite, R.id.jinxite, R.id.liaonte, R.id.jilinte, R.id.heite, R.id.suzte,
            R.id.zhete, R.id.wante, R.id.minte, R.id.gante, R.id.lute, R.id.yuwte, R.id.eyute, R.id.xiangte, R.id.yuete, R.id.qiongte,
            R.id.sichuante, R.id.guizhoute, R.id.yunnante, R.id.shanxite, R.id.gansute, R.id.qinghaite, R.id.neimengte, R.id.guiguangte, R.id.ningxiate, R.id.xinjiangte,
            R.id.shengfente, R.id.xizte, R.id.shiguangte, R.id.lingshite, R.id.jingchate, R.id.xuete, R.id.xgangte, R.id.aomente, R.id.jpscli,

            R.id.yi1te, R.id.er2te, R.id.ss3, R.id.ss4, R.id.ww5, R.id.ll6, R.id.qq7, R.id.bb8, R.id.jj9, R.id.ll0,
            R.id.qq_q, R.id.ww_w, R.id.ee_e, R.id.rr, R.id.tt, R.id.yy, R.id.uu, R.id.pp,
            R.id.aa, R.id.ss, R.id.dd, R.id.ff, R.id.gg, R.id.hh, R.id.jj, R.id.kk, R.id.ll,
            R.id.shengfente2, R.id.zz, R.id.xx, R.id.cc, R.id.vv, R.id.bb, R.id.nn, R.id.mm, R.id.jpscli2})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_single:
            case R.id.text_single:
            case R.id.single_ly:
                if(isSingle == 2){
                    singleButton.setBackgroundResource(R.mipmap.auth_follow_cb_chd);
                    isSingle = 1;
                }else{
                    singleButton.setBackgroundResource(R.mipmap.auth_follow_cb_unc);
                    isSingle = 2;
                }
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_menu:
//                popupMenu.showLocation(R.id.iv_menu);// 设置弹出菜单弹出的位置
//                // 设置回调监听，获取点击事件
//                popupMenu.setOnItemClickListener(new OnItemClickListener() {
//
//                    @Override
//                    public void onClick(MENUITEM item, String str) {
//                        // TODO Auto-generated method stub
//                        Toast.makeText(MessageActivity.this, str, Toast.LENGTH_LONG).show();
//                    }
//                });
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_value:
                selectViewIndex = 0;
                mSpinerPopWindow.setWidth(tvValue.getWidth());
                mSpinerPopWindow.showAsDropDown(tvValue);
                mSpinerPopWindow.setDate(compayNamelist);
                setTextImage(R.drawable.icon_down);
                break;
            case R.id.tv_value1:
                selectViewIndex = 1;
                mSpinerPopWindow.setWidth(tvValue1.getWidth());
                mSpinerPopWindow.showAsDropDown(tvValue1);
                mSpinerPopWindow.setDate(compayNamelist);
                setTextImage(R.drawable.icon_down);
                break;
            case R.id.tv_value2:
                selectViewIndex = 2;
                mSpinerPopWindow.setWidth(tvValue2.getWidth());
                mSpinerPopWindow.showAsDropDown(tvValue2);
                mSpinerPopWindow.setDate(itemNamelist);
                setTextImage(R.drawable.icon_down);
                break;
            case R.id.btn_send_message:{
//                bluetoothPrinterTest();
                String url = "http://"+baseUrl+"/mqttmsg!saveone.do";
                String company = tvValue.getText().toString();
                String company1 = tvValue1.getText().toString();
                String product = tvValue2.getText().toString();
                String companyId ="";
                String company1Id = "";
                String productId= "";
                for(String key : compayKeyList.keySet()){
                    if(compayKeyList.get(key).equals(company)){
                        companyId = key;
                    }
                    if(compayKeyList.get(key).equals(company1)){
                        company1Id = key;
                    }else if(compayKeyList.get(key).equals(product)){
                        productId = key;
                    }
                }
                String car = sendTopic.getText().toString();
                String note = sendMessage.getText().toString();
                String which;
                which = title.getText().toString();
//                which = "1111111";
                submit(url,car,companyId,productId,company1Id,note,which);
//                saveImg(promptView);
                //
                break;
            }
            case R.id.btn_modify:{
                if(isModifyButton){
                    shengli.setVisibility(View.VISIBLE);
                    haomali.setVisibility(View.GONE);
                    modifyButtonn.setText("完成");
                    isModifyButton = false;
                }else{
                    shengli.setVisibility(View.GONE);
                    haomali.setVisibility(View.GONE);
                    modifyButtonn.setText("修改");
                    isModifyButton = true;
                }

                break;
            }
            case R.id.shengfente:{
                shengli.setVisibility(View.GONE);
                haomali.setVisibility(View.VISIBLE);
                break;
            }
            case R.id.shengfente2:{
                shengli.setVisibility(View.VISIBLE);
                haomali.setVisibility(View.GONE);
                break;
            }
            case R.id.jpscli:
            case R.id.jpscli2:{
                if(sendTopic != null){
                    sendTopic.dispatchKeyEvent(new KeyEvent(
                            KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
                }
                break;
            }

            default:{
                if(v instanceof TextView){
                    TextView textView = (TextView) v;
                    String text = (String)((TextView) v).getText();
                    if(sendTopic != null){
                        int index = sendTopic.getSelectionStart();
                        Editable editable =  sendTopic.getText();
                        editable.insert(index,text);
                }

                }
            }

        }

    }

    private void sendMessage(){
        Message msg = new Message();
        msg.what = 4;
        handler.sendMessage(msg);
    }


    private void startReconnect() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {

            @Override
            public void run() {
                if(!client.isConnected()) {
                    connect();
                }
            }
        }, 0 * 1000, 10 * 1000, TimeUnit.MILLISECONDS);
    }

    private void init() {
        ButterKnife.bind(this);
        promptView = findViewById(R.id.prompt_view);
        shengli.setVisibility(View.GONE);
        haomali.setVisibility(View.GONE);
        carNoImg =  findViewById(R.id.carNoImg);

        btnSendMessage = (Button)findViewById(R.id.btn_send_message);
        if("自动".equals(isAuto)){
            btnSendMessage.setBackgroundResource(R.color.content_color);
            btnSendMessage.setClickable(false);
            btnSendMessage.setEnabled(false);
        }

        modifyButtonn = (Button)findViewById(R.id.btn_modify);
        sendTopic =  (EditText)findViewById(R.id.send_topic);
        sendTopic.setFocusable(false);
        sendTopic.setShowSoftInputOnFocus(false);
        sendMessage = (EditText)findViewById(R.id.et_message);
        popupMenu = new PopupMenu(this);
        singleButton = findViewById(R.id.btn_single);
        iv_menu = (ImageView) findViewById(R.id.iv_menu);
//        iv_menu.setOnClickListener(this);
//        ((TextView) findViewById(R.id.account)).setText(clientId);
        title = (TextView) findViewById(R.id.choice);
//        checkBox = findViewById(R.id.btn_single);
//        checkBox.setOnCheckedChangeListener(this);
        try {
            //host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
            client = new MqttClient("tcp://"+host+":"+prot,"" ,
                    new MemoryPersistence());
//            Log.i("lymain", "clientId=" + clientId);
            //MQTT的连接设置
            options = new MqttConnectOptions();
            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
            //设置连接的用户名
            options.setUserName(userName);
            Log.i("lymain", "userName=" + userName);
            Log.i("lymain", "password=" + password);
            //设置连接的密码
            options.setPassword(password.toCharArray());
            options.setCleanSession(true);
            options.setKeepAliveInterval(60);
//            client.subscribe(myTopic);
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            //设置回调
            client.setCallback(new MqttCallback() {

                @Override
                public void connectionLost(Throwable cause) {
                    //连接丢失后，进行重连
                    Log.i("lymain", "connectionLost----------");
                    Message msg = new Message();
                    msg.what = 3;
                    handler.sendMessage(msg);
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    //发布后会执行到这里
                    Log.i("lymain", "deliveryComplete---------" + token.isComplete());
                }

                @Override
                public void messageArrived(String topicName, MqttMessage message)
                        throws Exception {
//                    byte[] s = message.toString().getBytes();
//                   String ss =  new String(s,"UTF-8");
//                   String ssss = stringToHex(ss);
                    //subscribe后得到的消息会执行到这里面
//                    Log.i("baoshan", "messageArrived---------"+message.toString() +"ssss["+ssss+"]");
                    parserData(message.toString());
//                    parserData(ssss);
//                    Message msg = new Message();
//                    msg.what = 1;
//                    msg.obj = topicName+"---"+message.toString();
//                    handler.sendMessage(msg);
                }
            });
            // connect();
        } catch (Exception e) {
            Log.e("baoshan","message:["+e.toString()+"}");
            e.printStackTrace();
        }
        getCompanny("http://"+baseUrl+"/mqttmsg!company.do",compayIdlist,compayNamelist);
        getCompanny("http://"+baseUrl+"/mqttmsg!item.do",itemIdlist,itemNamelist);
    }

    private void connect() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Log.i("lymain", "connect3");
                    //链接服务端
                    client.connect(options);
                    Log.i("lymain", "connect1");
                    Message msg = new Message();
                    msg.what = 2;
                    handler.sendMessage(msg);
                    Log.i("lymain", "connect2");
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("lymain", "connectException：【"+e.toString());
                    Message msg = new Message();
                    msg.what = 3;
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(client != null && keyCode == KeyEvent.KEYCODE_BACK) {
            try {
                client.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            scheduler.shutdown();
            client.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter printerStatusFilter = new IntentFilter();
        printerStatusFilter.addAction(blutetoothPrinterUtils.PRINTER_NORMAL_ACTION);
        printerStatusFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        printerStatusFilter.addAction(blutetoothPrinterUtils.GET_CUST_PRINTAPP_PACKAGENAME_ACTION);

        registerReceiver(blutetoothPrinterUtils.IPosPrinterStatusListener,printerStatusFilter);

//        loopPrintFlag = DEFAULT_LOOP_PRINT;
        blutetoothPrinterUtils.LoadBluetoothPrinter();
    }


    public void parserData(String revMsg){

        if(revMsg.startsWith("AT*GPO") || revMsg.startsWith("OK")|| revMsg.length()<8){
            return;
        }

        String msg = revMsg.substring(0,8);
        String shows = null;
        boolean isjson = false;
        org.json.JSONObject rjsonreq = null;
        revMsg = revMsg.replaceAll(" ","");

        revMsg = revMsg.trim();
        if(revMsg.startsWith("+")){
             revMsg = stringToHex(revMsg);
        }
        Log.e("baoshan","parserData:["+revMsg+"]");
        if (msg.endsWith("=")) {
            try {
                msg = msg.substring(0, 7);

                msg = new StringBuffer(msg).reverse().toString();
                // msg=msg.substring(port)
//                int num=Integer.valueOf(msg) + "";
                shows =  Integer.valueOf(msg) + "";
                Message msg1 = new Message();
                msg1.what = 1;
                msg1.obj = shows;
                handler.sendMessage(msg1);
            } catch (Exception e) {
Log.e("baoshan","parserData err:["+e.toString()+"]");
                e.printStackTrace();
            }
            // 0012000=
//        } else if (revMsg.endsWith("03")) {
           // revMsg = revMsg.replaceAll(" ","");

            revMsg = revMsg.trim();
//            String[] temp = new String[12];
//            try {
//                if (msg.length() < 24)
//                    msg = "02" + msg;
//
////							for(int i=0;i<len/24;i++)
//                // for (int i = 0; i < 1; i++) {
//                int i = 0;
//                String da = msg.substring(i * 24, i * 24 + 24);
//                // System.out.println(d);
//                for (int j = 0; j < 12; j++) {
//                    temp[j] = da.substring(j * 2, j * 2 + 2);
//                    // System.out.print(temp[j]+"_");
//                }
//                // System.out.println();
//                String num = "";
//                int nn = Integer.valueOf(temp[8]) - 30;
//
//                for (int j = 2; j < 8; j++) {
//                    num += (Integer.valueOf(temp[j]) - 30);
//                }
//                if ("2d".equals(temp[1]))
//                    num = "-" + num;
//
//                num = Integer.valueOf(num) + "";
//                // nn=4;
//                if (nn > 0)
//                    num = num.substring(0, num.length() - nn) + "." + num.substring(num.length() - nn);
//
//
//                shows = "num ";
//                Message msg1 = new Message();
//                msg1.what = 1;
//                msg1.obj = shows;
//                handler.sendMessage(msg1);
//            } catch (Exception e) {
//                Log.e("baoshan","parserData1:["+e.toString()+"]");
//                e.printStackTrace();
//            }

        }else if (revMsg.startsWith("2b") || revMsg.startsWith("2d") || revMsg.startsWith("022")) {

//								Date d = new Date();
            // String time=DateHelper.sdf.format(d);
//								String cday = DateHelper.sdfsp.format(d);
            if (revMsg.length() < 24)
                    revMsg = "02" + revMsg;
            String[] temp = new String[12];

//					for(int i=0;i<len/24;i++)
            // for (int i = 0; i < 1; i++) {
            int i = 0;
            revMsg = revMsg.replaceAll(" ","");

            revMsg = revMsg.trim();
            String da = revMsg.substring(0, 22);
            // System.out.println(d);
            for (int j = 0; j < 11; j++) {
                temp[j] = da.substring(j * 2, j * 2 + 2);
                // System.out.print(temp[j]+"_");
            }
            // System.out.println();
            String num = "";
            int nn = Integer.valueOf(temp[8]) - 30;

            for (int j = 2; j < 8; j++) {
                num += (Integer.valueOf(temp[j]) - 30);
            }
            if ("2D".equals(temp[1]))
                num = "-" + num;

            num = Integer.valueOf(num) + "";
            // nn=4;
            if (nn > 0)
                num = num.substring(0, num.length() - nn) + "."
                        + num.substring(num.length() - nn);

            System.out.println(num + "-----" + nn + "____");

            shows = "{\"code\":\"weight\",\"valu\":\"" + num + "\",\"time\":\""
                    + System.currentTimeMillis() + "\"}";
            Message msg1 = new Message();
            msg1.what = 1;
            msg1.obj = num;
            handler.sendMessage(msg1);
        } else if (revMsg.startsWith("+GPIINFO:")) {

            String [] result = revMsg.split(",");

            shows = "{\"code\":\"infrared\",\"valu\":\"" + revMsg.substring(9) + "\"}";
            System.out.println("--+GPIINFO:---" + shows + "____");
            Message msg1 = new Message();
            msg1.what = 7;
            msg1.obj = result;
            handler.sendMessage(msg1);
        }else if (revMsg.endsWith("3D")) {

            String xy2 = revMsg.substring(0, 16);

            String[] temp = new String[7];

//									for(int i=0;i<len/24;i++)
            // for (int i = 0; i < 1; i++) {
            int i = 0;
            // String da = data.substring(i * 24, i * 24 + 24);
            // System.out.println(d);
            for (int j = 0; j < 7; j++) {
                temp[j] = xy2.substring(j * 2, j * 2 + 2);
                // System.out.print(temp[j]+"_");
            }

            String num = "";
            int nn = Integer.valueOf(temp[6]) - 30;

            for (int j = 6; j > -1; j--) {
                num += (Integer.valueOf(temp[j]) - 30);
            }
            num = Integer.valueOf(num) + "";
            shows = "{\"code\":\"weight\",\"valu\":\"" + num + "\",\"time\":\""
                    + System.currentTimeMillis() + "\"}";
        } else {
            try {

                rjsonreq = new org.json.JSONObject(revMsg);
                isjson = true;
            } catch (Exception e) {
                Log.e("baoshan", "parserData2:[" + e.toString() + "]");
                e.printStackTrace();
            }

            // System.out.println("time:"+new Date());
            // System.out.println("time:"+(System.currentTimeMillis()-start));
            if (isjson) {

                try {
                    Carbean carbean = GsonFomater.format(revMsg, Carbean.class);
                    // rjsonreq = new org.json.JSONObject(msg);
                    if (carbean != null && carbean.code.equals("car")) {
                        Message msg1 = new Message();
                        msg1.what = 5;
                        msg1.obj = carbean;
                        handler.sendMessage(msg1);
                    }
                    String docId = rjsonreq.getString("ID");
                    org.json.JSONObject reported = rjsonreq.getJSONObject("reported");
                    int len = reported.getInt("len");
                    System.out.println(len);
                    String data = reported.getString("data");



                } catch (Exception e) {
                    Log.e("baoshan", "parserData3:[" + e.toString() + "]");
                    e.printStackTrace();

                }
            }
        }
if(shows == null ){
    shows = "shows is NULL";
}
//Log.e("baoshan",shows);









    }
//    private BroadcastReceiver IPosPrinterStatusListener = new BroadcastReceiver(){
//        @Override
//        public void onReceive(Context context, Intent intent){
//            String action = intent.getAction();
//            if(action == null)
//            {
//                Log.d(TAG,"IPosPrinterStatusListener onReceive action = null");
//                return;
//            }
//            // Log.d(TAG,"IPosPrinterStatusListener action = "+action);
//            if(action.equals(PRINTER_NORMAL_ACTION))
//            {
//                mPrinterHandler.sendEmptyMessageDelayed(MSG_IS_NORMAL,0);
//            }
//            else if(action.equals(BluetoothAdapter.ACTION_STATE_CHANGED))
//            {
//                int state= intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,BluetoothAdapter.ERROR);
//                switch (state) {
//                    case BluetoothAdapter.STATE_OFF:
//                        Log.d("aaa", "STATE_OFF 蓝牙关闭");
//                        isBluetoothOpen = false;
//                        break;
//                    case BluetoothAdapter.STATE_TURNING_OFF:
//                        Log.d("aaa", "STATE_TURNING_OFF 蓝牙正在关闭");
//                        isBluetoothOpen = false;
//                        if(mBluetoothAdapter != null)
//                            mBluetoothAdapter = null;
//                        if(mBluetoothPrinterDevice != null)
//                            mBluetoothPrinterDevice = null;
//                        try {
//                            if (socket != null && (socket.isConnected())) {
//                                socket.close();
//                                socket = null;
//                            }
//                        }
//                        catch (IOException e)
//                        {
//                            e.printStackTrace();
//                        }
//                        break;
//                    case BluetoothAdapter.STATE_ON:
//                        Log.d("aaa", "STATE_ON 蓝牙开启");
//                        loopPrintFlag = DEFAULT_LOOP_PRINT;
//                        isBluetoothOpen = true;
//                        blutetoothPrinterUtils.LoadBluetoothPrinter();
//                        break;
//                    case BluetoothAdapter.STATE_TURNING_ON:
//                        isBluetoothOpen = true;
//                        Log.d("aaa", "STATE_TURNING_ON 蓝牙正在开启");
//                        break;
//                }
//            }
//            else if(action.equals(GET_CUST_PRINTAPP_PACKAGENAME_ACTION))
//            {
//                String mPackageName = intent.getPackage();
//                Log.d(TAG,"====GET_CUST_PRINTAPP_PACKAGENAME_ACTION："+action+"=======mPackageName:"+mPackageName);
//            }
//            else
//            {
//                mPrinterHandler.sendEmptyMessageDelayed(MSG_TEST,0);
//            }
//        }
//    };

//    public void LoadBluetoothPrinter()
//    {
//        // 1: Get BluetoothAdapter
//        mBluetoothAdapter = BluetoothUtil.getBluetoothAdapter();
//        if(mBluetoothAdapter == null)
//        {
//            //Toast.makeText(getBaseContext(), R.string.get_BluetoothAdapter_fail, Toast.LENGTH_LONG).show();
//            isBluetoothOpen = false;
//            return;
//        }
//        else
//        {
//            isBluetoothOpen =true;
//        }
//        //2: Get bluetoothPrinter Devices
//        mBluetoothPrinterDevice = BluetoothUtil.getIposPrinterDevice(mBluetoothAdapter);
//        if(mBluetoothPrinterDevice == null)
//        {
//            //Toast.makeText(getBaseContext(), R.string.get_BluetoothPrinterDevice_fail, Toast.LENGTH_LONG).show();
//            return;
//        }
//        //3: Get conect Socket
//        try {
//            socket = BluetoothUtil.getSocket(mBluetoothPrinterDevice);
//        }
//        catch (IOException e)
//        {
//            e.printStackTrace();
//            return;
//        }
//        //Toast.makeText(getBaseContext(), R.string.get_BluetoothPrinterDevice_success, Toast.LENGTH_LONG).show();
//    }

//    public int getPrinterStatus()
//    {
//        byte[] statusData = new byte[3];
//        if(!isBluetoothOpen)
//        {
//            printerStatus = PRINTER_ERROR_UNKNOWN;
//            return printerStatus;
//        }
//        if((socket == null) || (!socket.isConnected()))
//        {
//            try {
//                socket = BluetoothUtil.getSocket(mBluetoothPrinterDevice);
//            }
//            catch (IOException e)
//            {
//                e.printStackTrace();
//                return printerStatus;
//            }
//        }
//        try {
//            InputStream in = socket.getInputStream();
//            OutputStream out = socket.getOutputStream();
//            byte[] data = ESCUtil.getPrinterStatus();
//            out.write(data,0,data.length);
//            int readsize = in.read(statusData);
//            //Log.e(TAG,"~~~ readsize:"+readsize+" statusData:"+statusData[0]+" "+statusData[1]+" "+statusData[2]);
//            if((readsize > 0) &&(statusData[0] == ESCUtil.ACK && statusData[1] == 0x11)) {
//                printerStatus = statusData[2];
//            }
//            out.close();
//            in.close();
//            socket.close();
//        }
//        catch (IOException e)
//        {
//            e.printStackTrace();
//        }
//
//        return printerStatus;
//    }
//

//    private void bluetoothPrinterTest(ArrayList<DataBean> list)
//    {
//        DataBean dataBean = list.get(0);
//
//        ThreadPoolManager.getInstance().executeTask(new Runnable() {
//            @Override
//            public void run() {
//                try{
//                    byte[] printer_init = ESCUtil.init_printer();
//                    byte[] fontSize0 = ESCUtil.fontSizeSet((byte) 0x00);
//                    byte[] fontSize1 = ESCUtil.fontSizeSet((byte) 0x01);
//                    byte[] fontSize2 = ESCUtil.fontSizeSet((byte) 0x10);
//                    byte[] fontSize3 = ESCUtil.fontSizeSet((byte) 0x11);
//                    byte[] lineH0 = ESCUtil.setLineHeight((byte)26);
//                    byte[] lineH1 = ESCUtil.setLineHeight((byte)50);
//
//                    byte[] align0 = ESCUtil.alignMode((byte)0);
//                    byte[] align1 = ESCUtil.alignMode((byte)1);
//                    byte[] align2 = ESCUtil.alignMode((byte)2);
//                    byte[] title1 = "称重结果\n".getBytes("GBK");
//                    String companys = MessageActivity.compayKeyList.get(dataBean.company);
//                    String company1s = MessageActivity.compayKeyList.get(dataBean.company2);
//                    String products = MessageActivity.compayKeyList.get(dataBean.product);
//                    byte[] title2 = "\n".getBytes("GBK"); //
//                    byte[] sign1 = "********************************\n".getBytes("GBK");
//                    String company = "收货单位："+companys+"\n";
//                    byte[] fontTest0 = company.getBytes("GBK");
//                    String company1 = "发货单位："+company1s+"\n";
//                    byte[] fontTest1 = company1.getBytes("GBK");
//                    String product = "货名："+products+"\n";
//                    byte[] fontTest2 = product.getBytes("GBK");
//                    String weight = "净重："+dataBean.weight1+"\n";
//                    byte[] fontTest3 = weight.getBytes("GBK");
//                    String car = "车牌："+dataBean.car+"\n";
//                    byte[] orderSerinum = car.getBytes("GBK");
//                    String note = "备注："+dataBean.note+"\n";
//                    byte[] specialSign= note.getBytes("GBK");
//                    String bianhao = "编号："+dataBean.cserial+"\n";
//                    byte[] testSign2 = bianhao.getBytes("GBK");
//                    String time = "时间："+dataBean.ctime+"\n";
//                    byte[] testInfo = time.getBytes("GBK");
//                    byte[] testSign = "--------------------------------\n".getBytes("GBK");
//                    byte[] nextLine = ESCUtil.nextLines(1);
//                    byte[] performPrint = ESCUtil.performPrintAndFeedPaper((byte)200);
//
//                    byte[][] cmdBytes = {printer_init,lineH0,fontSize3,align1,title1,fontSize1,title2,nextLine,align0,
//                            fontSize0,sign1,fontSize0,fontTest0,lineH1,fontSize1,fontTest1,lineH0,fontSize2,fontTest2,
//                            lineH1,fontSize3,fontTest3,align2,lineH0,fontSize0,orderSerinum,specialSign,testSign,
//                            align1,fontSize1,lineH1,testInfo,nextLine,performPrint};
//                    try {
////                        if(mBluetoothPrinterDevice == null){
////                            return;
////                        }
//                        if((socket == null) || (!socket.isConnected()))
//                        {
//                            socket = BluetoothUtil.getSocket(mBluetoothPrinterDevice);
//                        }
//                        byte[] data = ESCUtil.byteMerger(cmdBytes);
//                        OutputStream out = socket.getOutputStream();
//                        out.write(data,0,data.length);
//                        out.close();
//                        socket.close();
//                    }
//                    catch (IOException e)
//                    {
//                        e.printStackTrace();
//                    }
//                }
//                catch (UnsupportedEncodingException e)
//                {
//                    e.printStackTrace();
//                }
//
//            }
//        });
//    }
//    /**
//     * 消息处理
//     */
//    private HandlerUtils.IHandlerIntent mHandlerIntent = new HandlerUtils.IHandlerIntent()
//    {
//        @Override
//        public void handlerIntent(Message msg)
//        {
//            Log.d(TAG,"-----------msg.what:"+msg.what);
//            switch (msg.what)
//            {
//                case MSG_TEST:
//                    break;
//                case MSG_IS_NORMAL:
//                    if ( blutetoothPrinterUtils.getPrinterStatus() == PRINTER_NORMAL) {
//                         blutetoothPrinterUtils.print_loop(loopPrintFlag);
//                    }
//                    break;
//                default:
//                    break;
//            }
//        }
//    };


    public  void getCompanny(String url,ArrayList<String>idList,ArrayList<String>nameList) {

        Map<String, String> params = new HashMap<>();
        AFinalHttp.requestForGet(url, params, null,new AFinalHttp.CallBack(context) {

            @Override
            protected void success(Object data) {
                parsedata(data.toString(),idList,nameList);
                if(nameList!= null && nameList.size() >0){

//                    Message msg = new Message();
//                    msg.what = 4;
//                    handler.sendMessage(msg);
                }
                else {
                    Utils.toast("获取数据成功");
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg){
                 Log.e("baoshann",strMsg);
            }
        });

    }


    public void  parsedata(String json,ArrayList<String>idList, ArrayList<String> nameList){
        ArrayList<Company.CompanyBeann> list = new ArrayList<>();
        if(json != null){
            json = json.substring(1,json.length()-1);
            String[] s = json.split(",");
            if(s != null){
                for(int i = 0;i <s.length;i++){
                    String  strS = s[i];
                    String[] stringData = strS.split(":");
                    String id = stringData[0].substring(1,stringData[0].length()-1);
                    String name = stringData[1].substring(1,stringData[1].length()-1);
                    compayKeyList.put(id,name);
                    idList.add(id);
                    nameList.add(name);
                }

            }
        }

    }

//    private View.OnClickListener clickListener = new View.OnClickListener() {
//        @Override
//        public void onClick(View v) {
//            switch (v.getId()) {
//                case R.id.tv_value:
//                    mSpinerPopWindow.setWidth(tvValue.getWidth());
//                    mSpinerPopWindow.showAsDropDown(tvValue);
//                    setTextImage(R.drawable.icon_down);
//                    break;
//            }
//        }
//    };
    /**
     * ��TextView�ұ�����ͼƬ
     * @param resId
     */
    private void setTextImage(int resId) {
        Drawable drawable = getResources().getDrawable(resId);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(),drawable.getMinimumHeight());// ��������ͼƬ��С��������ʾ
        tvValue.setCompoundDrawables(null, null, drawable, null);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked){
                checkBox.setBackgroundResource(R.mipmap.auth_follow_cb_chd);
            }else{
                checkBox.setBackgroundResource(R.mipmap.auth_follow_cb_unc);
            }
    }

    private void submit(String url,String car,String company,String product,String company2,String note,String weight2){

        Map<String, String> params = new HashMap<>();
        params.put("which",isSingle+"");
        params.put("id",MessageActivity.currentId);
        params.put("mqttMsg1.car",car);
        params.put("mqttMsg1.company",company);
        params.put("mqttMsg1.product",product);
        params.put("mqttMsg1.company2",company2);
        params.put("mqttMsg1.note",note);
        params.put("mqttMsg1.weight2",weight2);
        params.put("view","json");
        AFinalHttp.requestForPost(url, params, null,new AFinalHttp.CallBack(context) {

            @Override
            protected void success(Object data) {
               String ss =  data.toString();
               Log.e("baoshan","ss:["+ss+"]");

                if(ss != null){
                    ResultBean resultBean = GsonFomater.format(ss,ResultBean.class);
                    int totalCount = resultBean.totalCount;
                    if(resultBean != null && resultBean.result != null && resultBean.result.size() >0){
//                        bluetoothPrinterTest(resultBean.result);
//                        multiThreadPrintTest(resultBean.result);

                        carNoImg.setImageResource(R.drawable.chat_tool_photo);
                        sendTopic.setText("");
                        sendMessage.setText("");
                        if(resultBean.result.get(0).cday.equals("1")){
                            dataToView(resultBean,resultBean.result.get(0).cday);
                        }

                    }
                }


//                parsedata(data.toString(),idList,nameList);
//                if(nameList!= null && nameList.size() >0){
//
////                    Message msg = new Message();
////                    msg.what = 4;
////                    handler.sendMessage(msg);
//                }
//                else {
//                    Utils.toast("获取数据成功");
//                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg){
                Log.e("baoshann",strMsg);
            }
        });
    }

    private void dataToView(ResultBean resultBean,String cday){
        Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/fangsong.ttf");
        Typeface typeface1 = Typeface.createFromAsset(getAssets(), "fonts/jianti.ttf");

//使用字体成仿宋体
        tv_item.setTypeface(typeface);
        tv_item1.setTypeface(typeface);
        tv_item2.setTypeface(typeface);
        tv_item3.setTypeface(typeface);
        tv_item4.setTypeface(typeface);
        tv_item5.setTypeface(typeface);
        tv_item6.setTypeface(typeface);
        tv_item7.setTypeface(typeface);
        tv_item8.setTypeface(typeface);
        tv_item9.setTypeface(typeface);
        tv_item10.setTypeface(typeface);
        value_item.setTypeface(typeface1);
        value_item1.setTypeface(typeface1);
        value_item2.setTypeface(typeface1);
        value_item3.setTypeface(typeface1);
        value_item4.setTypeface(typeface1);
        value_item5.setTypeface(typeface1);
        value_item6.setTypeface(typeface1);
        value_item7.setTypeface(typeface1);
        value_item8.setTypeface(typeface1);
        value_item9.setTypeface(typeface1);
        value_item10.setTypeface(typeface1);
        String company = MessageActivity.compayKeyList.get(resultBean.result.get(0).company);
        String company1 = MessageActivity.compayKeyList.get(resultBean.result.get(0).company2);
        String product = MessageActivity.compayKeyList.get(resultBean.result.get(0).product);
        value_item.setText(company);
        value_item1.setText(company1);
        value_item2.setText(product);
        value_item3.setText(resultBean.result.get(0).weight2+"");
        value_item4.setText(resultBean.result.get(0).weight1+"");
        if(cday != null && cday.equals("1")){
            value_item5.setText(resultBean.result.get(0).weight2+"");
        }else{
            value_item5.setText(resultBean.result.get(0).weight1-resultBean.result.get(0).weight2+"");
        }
//        value_item5.setText(resultBean.result.get(0).weight1-resultBean.result.get(0).weight2+"");
        value_item6.setText(resultBean.result.get(0).car);
        value_item7.setText(resultBean.result.get(0).company);
        value_item8.setText(resultBean.result.get(0).note);
        value_item9.setText(resultBean.result.get(0).cserial);
        value_item10.setText(resultBean.result.get(0).ctime);
//        promptView
//        viewToBitmap(promptView);
        saveImg(promptView);

    }

    private Bitmap viewToBitmap(View v){
        int width = v.getWidth();
        int height = v.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        v.draw(canvas);
        return bitmap;
    }
    public String saveImg(View view) {
        Bitmap cachebmp = viewToBitmap(view);
        blutetoothPrinterUtils.printBitmapTest(cachebmp);
//        try {
//            String dir=
//                    Environment.getExternalStorageDirectory().getAbsolutePath()+"/share.png";
//            File f = new File(dir);
//            isGrantExternalRW(this);
//            if (!f.exists()) {
//                f.getParentFile().mkdirs();
//                f.createNewFile();
//            }
//            FileOutputStream out = new FileOutputStream(f);
//            cachebmp.compress(Bitmap.CompressFormat.PNG, 90, out);
//            out.flush();
//            out.close();
//            view.destroyDrawingCache();
//            return f.getAbsolutePath();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return null;
    }
    /**
     * 获取储存权限
     * @param activity
     * @return
     */

    public static boolean isGrantExternalRW(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && activity.checkSelfPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            activity.requestPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, 1);

            return false;
        }

        return true;
    }
    private void initShare(){
        host = (String)Constant.getValue(MessageActivity.this,Constant.mqttServer);
        prot = (String)Constant.getValue(MessageActivity.this,Constant.mqttServerPort);;
        userName= (String)Constant.getValue(MessageActivity.this,Constant.mqttUser);;
        password= (String)Constant.getValue(MessageActivity.this,Constant.mqttpassword);
        myTopic = (String)Constant.getValue(MessageActivity.this,Constant.mqttTopic);
        baseUrl = (String)Constant.getValue(MessageActivity.this,Constant.serverUrl);
        currentId = (String)Constant.getValue(MessageActivity.this,Constant.currentUserId);
        currentUser = (String)Constant.getValue(MessageActivity.this,Constant.currentUsername);
        clientName = (String)Constant.getValue(MessageActivity.this,Constant.clientname);
        isAuto = (String)Constant.getValue(MessageActivity.this,Constant.currentisAuto);
    }

    @Override
    public void onOpen() {

    }

    @Override
    public void onFailure(Exception e) {

    }

    @Override
    public void onTextMessage(String msg) {

    }

    @Override
    public void onClose(int code, String reason) {

    }


        public static String stringToHex(String input) {
            byte[] bytes = input.getBytes();
            BigInteger bigInteger = new BigInteger(1, bytes);
            String hex = bigInteger.toString(16);
            int paddingLength = (bytes.length * 2) - hex.length();
            if (paddingLength > 0) {
                return String.format("%0" + paddingLength + "d", 0) + hex;
            } else {
                return hex;
            }
        }



}